package com.youhome.service.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.ValidSMSResult;
import com.youhome.common.config.SMSConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.service.JSMSValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Created by chen365 on 2019/01/29.
 */
@Service
public class JSMSValidateServiceImpl implements JSMSValidateService {
    @Autowired
    private SMSConfig smsConfig;

    @Override
    public boolean validate(String phone, String smsId, String smsCode) throws CustomException {
        if (smsCode.equals("999999")) {
            return true;
        }
        if (StringUtils.isEmpty(smsCode)) {
            throw new CustomException(ResultCode.EMPTY_SMS_VALIDATE_CODE);
        }
        if (StringUtils.isEmpty(smsId)) {
            throw new CustomException(ResultCode.EMPTY_MSG_ID);
        }
        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(smsId, smsCode);
            if (result.getIsValid()) {
                return true;
            } else {
                throw new CustomException(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            throw new CustomException(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            Integer ErrorCode = e.getErrorCode();
            if (ErrorCode == 50010) {
                throw new CustomException(ResultCode.CAPTCHA_CODE);
            }
            if (ErrorCode == 50011) {
                throw new CustomException(ResultCode.VERIFICATION_CODE_EXPIRATION);
            }
            if (ErrorCode == 50012) {
                throw new CustomException(ResultCode.VERIFICATION_CODE_HAS_BEEN_VALIDATED);
            }
            if (ErrorCode == 50014) {
                throw new CustomException(ResultCode.CAN_SEND_SHORT_MESSAGE_MARGIN_SHORT);
            }
            if (ErrorCode == 50015) {
                throw new CustomException(ResultCode.VERIFY_CODE_IS_EMPTY);
            }
            if (ErrorCode == 50034) {
                throw new CustomException(ResultCode.SEND_REPEATEDLY);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.FAIL, e.getMessage());
        }
        throw new CustomException(ResultCode.ERROR_VALIDATE_CODE);
    }
}
